package main

import (
	"github.com/gorilla/mux"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"fmt"
	"path"
	"bytes"
	"html/template"
	"io/ioutil"
	"log"
)

// 提供 http服务
func startServer(port int) error {

	r := mux.NewRouter()
	r.HandleFunc("/{groupId}/{bookId}/{chapterId:\\d+}.html", bookDetail)
	r.HandleFunc("/main.css", mainCss)
	r.PathPrefix("/").Handler(http.FileServer(http.Dir(basedir)))
	err := http.ListenAndServe("127.0.0.1:"+string(port), r)
	if err != nil {
		log.Fatal("listen and serve :", err)
	}
	return err
}

func bookDetail(w http.ResponseWriter, r *http.Request) {
	var err interface{}
	defer func() {
		if err != nil {
			fmt.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("服务出错了"))
		}
	}()
	vars := mux.Vars(r)
	groupId, bookId, chapterId := vars["groupId"], vars["bookId"], vars["chapterId"]

	fileContent, err := ioutil.ReadFile(path.Join(basedir, groupId, bookId, chapterId+".html"))
	if err != nil {
		return
	}
	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(fileContent))
	if err != nil {
		return
	}
	var title = doc.Find("title").Text()
	var content, _ = doc.Find("body").Find("div").First().Html()
	var prevId, lastId = "", ""

	result := make(map[string]interface{})
	result["groupId"] = groupId
	result["bookId"] = bookId
	result["chapterId"] = chapterId
	result["title"] = title
	result["content"] = template.HTML(content)
	result["prevId"] = prevId
	result["lastId"] = lastId

	html, err := Render("frontDetail", result)
	if err == nil {
		fmt.Fprint(w, html)
	}
}

func mainCss(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "text/css")
	w.Write([]byte(tplMainCss))
}
